/*
 *
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: DevicesUtil.java
 *   @Date: 11/29/18 3:21 PM
 *   @Author: chenjun
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 *
 */

package io.bhex.baselib.utils;

import android.Manifest;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.DhcpInfo;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Vibrator;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.text.format.Formatter;
import android.util.DisplayMetrics;
import android.view.WindowManager;

import com.meituan.android.walle.WalleChannelReader;

import org.apache.commons.lang3.RandomStringUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import io.bhex.baselib.constant.Fields;
import io.bhex.baselib.core.CApplication;
import io.bhex.baselib.core.Preferences;

/**
 * Created by ppz on 2016/6/28.
 * 获取设备信息工具类
 */
public class DevicesUtil {

    private static HashMap<String, String> deviceParams;

    public static boolean isAppRunning(Context context, String packageName) {
        boolean isAppRunning = false;
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(100);
        if (list.size() <= 0) {
            return false;
        }
        for (ActivityManager.RunningTaskInfo info : list) {
            if (info.baseActivity.getPackageName().equals(packageName)) {
                return true;
            }
        }
        return false;
    }

    public static TelephonyManager getDeviceManager(Context context) {
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        return tm;
    }

    public static int getAppVersion(Context context) {
        int version = 0;
        try {
            version = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return version;
    }

    public static String getAppVersionName(Context context) {
        String versionName = "";
        try {
            versionName = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionName;
    }

    /**
     * 震动
     * @param context
     * @param milliseconds
     */
    public static void vibrate(Context context,long milliseconds) {
        Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
        vibrator.vibrate(milliseconds);
    }

    //获取本地IP
    public static String getLocalIpAddress() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface
                    .getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf
                        .getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress()) {
                        return inetAddress.getHostAddress();
                    }
                }
            }
        } catch (SocketException ex) {
            DebugLog.e("IpAddress", ex.toString());
        }
        return null;
    }

    /**
     * 获取网络地址
     * （在wifi状态下）
     *
     * @param ctx
     * @return
     */
    public static String getIPAddress(Context ctx) {
        WifiManager wifi_service = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE);
        DhcpInfo dhcpInfo = wifi_service.getDhcpInfo();
        WifiInfo wifiinfo = wifi_service.getConnectionInfo();
        DebugLog.i("IpAddress", "Wifi info----->" + wifiinfo.getIpAddress());
        DebugLog.i("IpAddress", "DHCP info gateway----->" + Formatter.formatIpAddress(dhcpInfo.gateway));
        DebugLog.i("IpAddress", "DHCP info netmask----->" + Formatter.formatIpAddress(dhcpInfo.netmask));
        //DhcpInfo中的ipAddress是一个int型的变量，通过Formatter将其转化为字符串IP地址
        return Formatter.formatIpAddress(dhcpInfo.ipAddress);
    }

    /**
     * 获取mac地址
     *
     * @return
     */
    public static String getMacAddress() {
        String result = "";
        String Mac = "";
//        result = DevicesUtil.callCmd("busybox ifconfig", "HWaddr");

        if (result == null) {
            return "--";
        }
        if (result.length() > 0 && result.contains("HWaddr")) {
            Mac = result.substring(result.indexOf("HWaddr") + 6, result.length() - 1);
            if (Mac.length() > 1) {
                result = Mac.toLowerCase();
            }
        }
        return result.trim();
    }

    /**
     * 执行命令
     *
     * @param cmd
     * @param filter
     * @return
     */
    public static String callCmd(String cmd, String filter) {
        String result = "";
        String line = "";
        try {
            Process proc = Runtime.getRuntime().exec(cmd);
            InputStreamReader is = new InputStreamReader(proc.getInputStream());
            BufferedReader br = new BufferedReader(is);

            //执行命令cmd，只取结果中含有filter的这一行
            while ((line = br.readLine()) != null && line.contains(filter) == false) {
                //result += line;
                DebugLog.i("test", "line: " + line);
            }

            result = line;
            DebugLog.i("test", "result: " + result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 获取设备id
     *
     * @return
     */
    public static String getDeviceName() {
//        android.os.Build.MODEL;
//        android.os.Build.VERSION.RELEASE;
        Build build = new Build();
        return Build.MODEL;
    }

    /**
     * 获取系统版本号
     *
     * @return
     */
    public static String getOS() {
        return android.os.Build.VERSION.RELEASE;
    }


    /**
     * 获取设备序列号
     *
     * @return
     */
    public static String getSerialNumber() {
        String serial = "";
        try {
            Class<?> c = Class.forName("android.os.SystemProperties");
            Method get = c.getMethod("get", String.class);
            serial = (String) get.invoke(c, "ro.serialno");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return serial;
    }

    /**
     * 获取Android id
     * @param context
     * @return
     */
    public static String getAndroidId(Context context) {
        String androidId = "";
        try {
            androidId = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return androidId;
    }

    /**
     * 获取国家码
     * @return
     */
    public static String getCountry(Context context) {
        Locale locale1 = context.getResources().getConfiguration().locale;
        return locale1.getCountry();

        //        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
        //            LocaleList locales = null;
        //            locales = context.getResources().getConfiguration().getLocales();
        //            for (int i = 0; i < locales.size(); i++) {
        //                Locale locale = locales.get(i);
        //                DebugLog.e("LOCAL",locale.getCountry()+"  "+locale.getDisplayCountry()+"  "+locale.getDisplayName()+"  "+locale.getDisplayLanguage());
        //
        //            }
        //        }
    }


    /**
     * 获取设备语言
     * @return
     */
    public static String getLocalLanguage(Context context) {
        Locale locale1 = context.getResources().getConfiguration().locale;
//        DebugLog.e("LNG","语言： "+locale1.getLanguage()+"  国家码："+getCountry(context));
        return locale1.getLanguage();
    }

    /**
     * 获取设备语言
     * @return
     */
    public static boolean isZh(Context context) {
        return DevicesUtil.getLocalLanguage(context).contains("zh");
    }

    /**
     * 获取网络
     * @return
     */
    public static String GetNetworkType(Context context) {
        String strNetworkType = "";
        ConnectivityManager cManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = cManager.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {
            if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                strNetworkType = "WIFI";
            } else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                strNetworkType = "2g/3g/4g";
                String _strSubTypeName = networkInfo.getSubtypeName();

                // TD-SCDMA   networkType is 17
                int networkType = networkInfo.getSubtype();
                switch (networkType) {
                    case TelephonyManager.NETWORK_TYPE_GPRS:
                    case TelephonyManager.NETWORK_TYPE_EDGE:
                    case TelephonyManager.NETWORK_TYPE_CDMA:
                    case TelephonyManager.NETWORK_TYPE_1xRTT:
                    case TelephonyManager.NETWORK_TYPE_IDEN: //api<8 : replace by 11
                        strNetworkType = "2G";
                        break;
                    case TelephonyManager.NETWORK_TYPE_UMTS:
                    case TelephonyManager.NETWORK_TYPE_EVDO_0:
                    case TelephonyManager.NETWORK_TYPE_EVDO_A:
                    case TelephonyManager.NETWORK_TYPE_HSDPA:
                    case TelephonyManager.NETWORK_TYPE_HSUPA:
                    case TelephonyManager.NETWORK_TYPE_HSPA:
                    case TelephonyManager.NETWORK_TYPE_EVDO_B: //api<9 : replace by 14
                    case TelephonyManager.NETWORK_TYPE_EHRPD:  //api<11 : replace by 12
                    case TelephonyManager.NETWORK_TYPE_HSPAP:  //api<13 : replace by 15
                        strNetworkType = "3G";
                        break;
                    case TelephonyManager.NETWORK_TYPE_LTE:    //api<11 : replace by 13
                        strNetworkType = "4G";
                        break;
                    default:
                        // http://baike.baidu.com/item/TD-SCDMA 中国移动 联通 电信 三种3G制式
                        if (_strSubTypeName.equalsIgnoreCase("TD-SCDMA") || _strSubTypeName.equalsIgnoreCase("WCDMA") || _strSubTypeName.equalsIgnoreCase("CDMA2000"))
                        {
                            strNetworkType = "3G";
                        }
                        else
                        {
                            strNetworkType = _strSubTypeName;
                        }

                        break;
                }
            }
        }
        return strNetworkType;
    }

    /**
     * 获取IMEI
     * @return
     */
    public static String getDeviceID(Context context) {
        String imei = getImei(context);
        if (TextUtils.isEmpty(imei)) {
            imei = getAndroidId(context);
        }
        else if (TextUtils.isEmpty(imei)) {
            imei = getMacAddress(context);
        }
        if (TextUtils.isEmpty(imei)) {
            Preferences sspUtil = Preferences
                    .getInstance(context.getApplicationContext());
            String recordImei = sspUtil.getRecordImei();
            if (TextUtils.isEmpty(recordImei)) {
                //String tempImei = "DIMEI"+ Math.round(Math.random() * 8999999999.0D + 1000000000.0D);
                String tempImei = RandomStringUtils.random(15);
                sspUtil.setRecordImei(tempImei);
                imei = tempImei;
            } else {
                imei = recordImei;
            }
        }
        return imei;
    }

    public static String getImei(Context context) {
        if (checkPermissions(context, "android.permission.READ_PHONE_STATE")) {
            TelephonyManager mTelephonyMgr = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            String deviceId = "";
            if (mTelephonyMgr != null)
                deviceId = mTelephonyMgr.getDeviceId();
            if (deviceId != null) {
                return deviceId;
            }
            return "";

        }
        return "";
    }

    public static boolean checkPermissions(Context context, String permission) {
        PackageManager localPackageManager = context.getPackageManager();

        return localPackageManager.checkPermission(permission,
                context.getPackageName()) == PackageManager.PERMISSION_GRANTED;
    }

    public static String getMacAddress(Context context) {
        if (checkPermissions(context, "android.permission.ACCESS_WIFI_STATE")) {
            WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            WifiInfo wifiInfo = wm.getConnectionInfo();
            if (wifiInfo != null) {
                String macAddress = wifiInfo.getMacAddress();
                if (macAddress != null) {
                    macAddress = macAddress.replace(":", "");
                    return macAddress;
                }
                return "";
            }

            return "";
        }

        return "";
    }

    public static String getSdkVersion(Context context) {
        String sdkVersion = "Android";
        //if (checkPermissions(context,"android.permission.READ_PHONE_STATE")) {
            sdkVersion = sdkVersion + Build.VERSION.RELEASE;
            //return sdkVersion;
        //}
        return sdkVersion;
    }

    public static String getScreenSize(Context context) {
        DisplayMetrics dm = new DisplayMetrics();
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        wm.getDefaultDisplay().getMetrics(dm);
        String screenSize = dm.widthPixels + "x" + dm.heightPixels;
        return screenSize;
    }

    public static String getIMSI(Context context) {
        String imsi = "";
        try {

            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
                TelephonyManager mTelephonyMgr = (TelephonyManager) context
                        .getSystemService(Context.TELEPHONY_SERVICE);
                if (mTelephonyMgr != null)
                    imsi = mTelephonyMgr.getSubscriberId();
            }
        } catch (Exception e) {
            return imsi;
        }
        return imsi;
    }

    public static String getManufacturer(Context context) {
        //if (checkPermissions(context, "android.permission.READ_PHONE_STATE")) {
            return Build.MANUFACTURER;
        //}
        //return "";
    }

    public static String getProduct(Context context) {
        //if (checkPermissions(context, "android.permission.READ_PHONE_STATE")) {
            return Build.PRODUCT;
        //}
        //return "";
    }

    public static String getPackageName(Context context) {
        String packName = "";
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), 0);
            // 当前应用的版本名称
            //			String versionName = info.versionName;
            // 当前版本的版本号
            //			int versionCode = info.versionCode;
            // 当前版本的包名
            packName = info.packageName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return packName;
    }

    public static String getChannel(Context context){
        //return getAppMetaData(context, "UMENG_CHANNEL");
        String channel = WalleChannelReader.getChannel(context);
        if(TextUtils.isEmpty(channel))
            channel = "official";
        return channel;
    }

    /**
     * 获取header、cookie中用的app name参数
     * @param context
     * @return
     */
    public static String getAppName(Context context){
        return "bhexApp";
    }


    /**
     * 初始化设备参数
     *
     * @return
     */
    public static void initDevicesParams(Application application) {
        deviceParams = new HashMap<>();
        try {
            deviceParams.put(Fields.PARAM_VERSION, DevicesUtil.getAppVersionName(application));
            deviceParams.put(Fields.PARAM_IMEI, DevicesUtil.getDeviceID(application));
            deviceParams.put(Fields.PARAM_PLATFORM, DevicesUtil.getSdkVersion(application));
            deviceParams.put(Fields.PARAM_MODEL, DevicesUtil.getManufacturer(application) + "+" + DevicesUtil.getProduct(application));
            deviceParams.put(Fields.PARAM_SCREEN_SIZE, DevicesUtil.getScreenSize(application));
            deviceParams.put(Fields.PARAM_IMSI, DevicesUtil.getIMSI(application));
            deviceParams.put(Fields.PARAM_APP,DevicesUtil.getAppName(application));

            deviceParams.put(Fields.PARAM_LBS, "");
            String userAgent = System.getProperty("http.agent");
            deviceParams.put("User-Agent", DevicesUtil.getAppName(application)+"/"+ DevicesUtil.getAppVersionName(application) + " " +userAgent);
            deviceParams.put(Fields.DEVICE_PARAM_OS, "Android");

            deviceParams.put(Fields.PARAM_NETT, DevicesUtil.GetNetworkType(CApplication.getInstance()));

        } catch (Exception e) {
            DebugLog.e(e);
        }
    }

    public static Map<String, String> getDeviceParams() {
        return deviceParams;
    }

}
